/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;

import com.anwen.mongo.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.comac.ins.common.core.domain.model.LoginUser;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.satoken.utils.LoginHelper;
import com.comac.ins.isfd.constant.enums.IsfdMongoQueryLogicalOperatorEnum;
import com.comac.ins.isfd.constant.enums.IsfdMongoQueryOperatorEnum;
import com.comac.ins.isfd.domain.DataRetrievalHistory;
import com.comac.ins.isfd.domain.IsfdDatabaseModelConfig;
import com.comac.ins.isfd.domain.IsfdDatabaseModelConfigField;
import com.comac.ins.isfd.domain.IsfdDatabaseMongoQuery;
import com.comac.ins.isfd.domain.bo.*;
import com.comac.ins.isfd.domain.vo.*;
import com.comac.ins.isfd.mapper.*;
import com.comac.ins.isfd.service.IIsfdDatabaseDataManagementService;
import com.comac.ins.isfd.service.IIsfdDatabaseMongoService;
import com.comac.ins.isfd.service.IsfdDataRetrievalService;
import com.comac.ins.system.domain.vo.SysUserVo;
import com.comac.ins.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @date: 2025/2/24 14:45
 **/
@RequiredArgsConstructor
@Service
public class IsfdDataRetrievalServiceImpl implements IsfdDataRetrievalService {
    @Autowired
    private final IsfdDataRetrievalMapper baseMapper;
    @Autowired
    private final IsfdDatabaseModelConfigMapper isfdDatabaseModelConfigMapper;
    @Autowired
    private IIsfdDatabaseMongoService mongoService;
    @Autowired
    private IsfdDatabaseModelConfigFieldMapper fieldMapper;
    @Autowired
    private IsfdBusinessDatabaseRefMapper IsfdBusinessDatabaseRefMapper;
    @Autowired
    private IsfdBusinessScenariosMapper isfdBusinessScenariosMapper;
    @Autowired
    private IsfdDatabaseTypeManagementMapper isfdDatabaseTypeManagementMapper;

    private final IIsfdDatabaseDataManagementService isfdDatabaseDataManagementService;

    private final ISysUserService userService;
    @Override
    public Long dataRetrievalCount() {
        // 查询所有的模型集合
        List<IsfdDatabaseModelConfig> modelConfig = isfdDatabaseModelConfigMapper.selectList();
        //循环统计所有模型的数据总数
        Long count = 0L;
        for (IsfdDatabaseModelConfig isfdDatabaseModelConfig : modelConfig) {
            String tableName = isfdDatabaseModelConfig.getTableName();
            // 调用MongoDB查询数据总量
            Long modelCount = mongoService.count(tableName);
            count+=modelCount;
        }
        return count;
    }

    @Override
    public IsfdDataRetrievalListVo dataRetrievalSearch(DataRetrievalHistoryBo dataRetrievalHistoryBo) {
        // 查询条件判断
        if(Objects.isNull(dataRetrievalHistoryBo)){
            // 返回所有的数据集合
            return null;
        }
        IsfdDataRetrievalListVo returnVo = new IsfdDataRetrievalListVo();
        // 业务场景列表
        List<IsfdBusinessScenariosVo> isfdBusinessScenariosList = new ArrayList<>();
        List<IsfdBusinessScenariosVo> isfdBusinessScenariosReturnList = new ArrayList<>();
        // 业务系统列表
        List<IsfdBusinessScenariosVo> isfdBusinessSystemsList = new ArrayList<>();
        List<IsfdBusinessScenariosVo> isfdBusinessSystemsReturnList = new ArrayList<>();
        // 模型列表
        List<IsfdDatabaseModelConfigSearchVo> isfdDatabaseModelConfigDataList = new ArrayList<>();
        List<IsfdDatabaseModelConfigVo> isfdDatabaseModelConfigReturnList = new ArrayList<>();
        // 要素库列表
        List<IsfdDatabaseTypeManagementVo> isfdDataBaseList = new ArrayList<>();
        //关联关系列表
        List<IsfdBusinessDatabaseRefVo> isfdBusinessDataBaseRefList = new ArrayList<>();
        // 查询业务系统
        isfdBusinessScenariosList = isfdBusinessScenariosMapper.selectScenariosByName(dataRetrievalHistoryBo.getSceneName(),0);
        // 查询业务场景
        isfdBusinessSystemsList = isfdBusinessScenariosMapper.selectScenariosByName(dataRetrievalHistoryBo.getSystemName(),1);
        List<IsfdDatabaseModelConfigVo> modelInfo = isfdDatabaseModelConfigMapper.selectModelByName(dataRetrievalHistoryBo.getModelName(),dataRetrievalHistoryBo.getStartTime(),dataRetrievalHistoryBo.getEndTime());
        // 判断查询条件的结果是否有值
        Boolean hasResult = true;
        if(isfdBusinessScenariosList.size() == 0 && isfdBusinessSystemsList.size() == 0 && modelInfo.size() == 0){
            hasResult = false;
        }
        if(isfdBusinessScenariosList.size() == 0 && StringUtils.isNotBlank(dataRetrievalHistoryBo.getSceneName())){
            hasResult = false;
        }
        if(isfdBusinessSystemsList.size() == 0 && StringUtils.isNotBlank(dataRetrievalHistoryBo.getSystemName())){
            hasResult = false;
        }
        if(modelInfo.size() == 0 && StringUtils.isNotBlank(dataRetrievalHistoryBo.getModelName())){
            hasResult = false;
        }
        // 初始化返回结果
        returnVo.setModelList(new ArrayList<>());
        returnVo.setSceneList(new ArrayList<>());
        returnVo.setSystemList(new ArrayList<>());
        returnVo.setDataBaseList(new ArrayList<>());
        returnVo.setDataList(new ArrayList<>());
        if(!hasResult){
            return returnVo;
        }
        Set parentModelIdSet = new HashSet();
        for (IsfdDatabaseModelConfigVo isfdDatabaseModelConfig : modelInfo) {
            if(Objects.isNull(isfdDatabaseModelConfig.getParentConfigId())){
                parentModelIdSet.add(isfdDatabaseModelConfig.getId());
            }else{
                IsfdDatabaseModelConfigVo modelVo = getParentModelId(isfdDatabaseModelConfig);
                parentModelIdSet.add(modelVo.getId());
            }
        }
        // 循环isfdBusinessScenariosList获取id
        List businessScenariosIds = new ArrayList();
        List businessSystemsIds = new ArrayList();
        List dataBaseTypeIds = new ArrayList();
        for (IsfdBusinessScenariosVo isfdBusinessScenariosVo : isfdBusinessScenariosList) {
            businessScenariosIds.add(isfdBusinessScenariosVo.getId());
        }
        for (IsfdBusinessScenariosVo isfdBusinessScenariosVo : isfdBusinessSystemsList) {
            businessSystemsIds.add(isfdBusinessScenariosVo.getId());
        }
        // 查询关联关系
        if(StringUtils.isNotBlank(dataRetrievalHistoryBo.getSystemName()) && businessSystemsIds.size()>0){
            isfdBusinessDataBaseRefList = IsfdBusinessDatabaseRefMapper.selectDataBaseRefByCondition(businessScenariosIds,businessSystemsIds,parentModelIdSet.stream().toList(),dataBaseTypeIds);
        }
        if(StringUtils.isBlank(dataRetrievalHistoryBo.getSystemName())){
            isfdBusinessDataBaseRefList = IsfdBusinessDatabaseRefMapper.selectDataBaseRefWithOutSystemName(businessScenariosIds,new ArrayList<>(),parentModelIdSet.stream().toList(),dataBaseTypeIds);
        }
        if(isfdBusinessDataBaseRefList.size() ==0){
            return returnVo;
        }
        // 分组场景
        Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedSceneDatas = isfdBusinessDataBaseRefList.stream()
            .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getSceneId));
        // 业务系统分组
        Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedSystemDatas = isfdBusinessDataBaseRefList.stream()
            .filter(p -> p.getSystemId() != null)
            .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getSystemId));
        // 要素库分组
        Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedDataBaseDatas = isfdBusinessDataBaseRefList.stream()
            .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getDatabaseTypeId));
        // 模型分组
        Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedModelDatas = isfdBusinessDataBaseRefList.stream()
            .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getParentModelId));
        for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedSceneDatas.entrySet()) {
            Long sceneId = entry.getKey();
            IsfdBusinessScenariosVo isfdBusinessScenariosVo = isfdBusinessScenariosMapper.selectVoById(sceneId);
            isfdBusinessScenariosReturnList.add(isfdBusinessScenariosVo);
        }
        for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedSystemDatas.entrySet()) {
            Long systemId = entry.getKey();
            IsfdBusinessScenariosVo isfdBusinessScenariosVo = isfdBusinessScenariosMapper.selectVoById(systemId);
            isfdBusinessSystemsReturnList.add(isfdBusinessScenariosVo);
        }
        for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedDataBaseDatas.entrySet()) {
            Long dataBaseId = entry.getKey();
            IsfdDatabaseTypeManagementVo isfdDatabaseTypeManagementVo = isfdDatabaseTypeManagementMapper.selectVoById(dataBaseId);
            if(isfdDatabaseTypeManagementVo.getParentId() == 0){
                isfdDataBaseList.add(isfdDatabaseTypeManagementVo);
            }else{
                IsfdDatabaseTypeManagementVo parentDataBase = getParentDataBase(isfdDatabaseTypeManagementVo);
                // 查询父级要素库
                isfdDataBaseList.add(parentDataBase);
            }
        }
        //isfdDataBaseList根据id去重
        List<IsfdDatabaseTypeManagementVo> distinctList = isfdDataBaseList.stream()
            .collect(Collectors.toMap(
                IsfdDatabaseTypeManagementVo::getId,   // 键：ID
                e -> e,            // 值：对象本身
                (oldVal, newVal) -> oldVal // 冲突时保留旧值
            ))
            .values()
            .stream()
            .collect(Collectors.toList());
        isfdDataBaseList = distinctList;
        // 循环模型
        for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedModelDatas.entrySet()) {
            Long modelId = entry.getKey();
            IsfdDatabaseModelConfigVo isfdDatabaseModelConfigVo = isfdDatabaseModelConfigMapper.selectVoById(modelId);
            isfdDatabaseModelConfigReturnList.add(isfdDatabaseModelConfigVo);
        }
        // 循环处理业务数据modelInfo
        for(IsfdDatabaseModelConfigVo isfdDatabaseModelConfig : modelInfo){
            IsfdDatabaseModelConfigSearchVo isfdDatabaseModelConfigSearchVo = new IsfdDatabaseModelConfigSearchVo();
            Long dataBaseRefModelId = null;
            if(Objects.nonNull(isfdDatabaseModelConfig.getParentConfigId())){
                IsfdDatabaseModelConfigVo isfdDatabaseModelConfigParent = getParentModelId(isfdDatabaseModelConfig);
                dataBaseRefModelId =  isfdDatabaseModelConfigParent.getId();
            }else{
                dataBaseRefModelId = isfdDatabaseModelConfig.getId();
            }
            // 判断父模型是否包含在isfdBusinessDataBaseRefList中
            for (IsfdBusinessDatabaseRefVo isfdBusinessDatabaseRefVo : isfdBusinessDataBaseRefList) {
                if(isfdBusinessDatabaseRefVo.getParentModelId().equals(dataBaseRefModelId)){
                    isfdDatabaseModelConfigSearchVo.setId(isfdDatabaseModelConfig.getId());
                    isfdDatabaseModelConfigSearchVo.setModelName(isfdDatabaseModelConfig.getModelName());
                    isfdDatabaseModelConfigSearchVo.setTableName(isfdDatabaseModelConfig.getTableName());
                    isfdDatabaseModelConfigSearchVo.setCreateTime(isfdDatabaseModelConfig.getCreateTime());
                    isfdDatabaseModelConfigSearchVo.setDescription(isfdDatabaseModelConfig.getDescription());
                    isfdDatabaseModelConfigSearchVo.setIsLastestVersion(isfdDatabaseModelConfig.getIsLastestVersion());
                    isfdDatabaseModelConfigSearchVo.setModelType(isfdDatabaseModelConfig.getModelType());
                    isfdDatabaseModelConfigSearchVo.setNodeId(isfdDatabaseModelConfig.getId());
                    isfdDatabaseModelConfigSearchVo.setIsPublished(isfdDatabaseModelConfig.getIsPublished());
                    isfdDatabaseModelConfigSearchVo.setParentConfigId(isfdDatabaseModelConfig.getParentConfigId());
                    isfdDatabaseModelConfigSearchVo.setVersionNumber(isfdDatabaseModelConfig.getVersionNumber());
                    isfdDatabaseModelConfigSearchVo.setNodeName(isfdDatabaseModelConfig.getModelName());
                    isfdDatabaseModelConfigSearchVo.setParentConfigFieldId(isfdDatabaseModelConfig.getParentConfigFieldId());
                    isfdDatabaseModelConfigSearchVo.setParentConfigFieldName(isfdDatabaseModelConfig.getParentConfigFieldName());
                    isfdDatabaseModelConfigSearchVo.setParentConfigName(isfdDatabaseModelConfig.getParentConfigName());
                    isfdDatabaseModelConfigSearchVo.setSceneId(isfdBusinessDatabaseRefVo.getSceneId());
                    isfdDatabaseModelConfigSearchVo.setSystemId(isfdBusinessDatabaseRefVo.getSystemId());
                    isfdDatabaseModelConfigSearchVo.setCreateBy(isfdDatabaseModelConfig.getCreateBy());
                    isfdDatabaseModelConfigSearchVo.setParentModelId(dataBaseRefModelId);
                    //查询用户中文名称
                    SysUserVo sysUser = userService.selectUserById(Long.valueOf(isfdDatabaseModelConfigSearchVo.getCreateBy()));
                    isfdDatabaseModelConfigSearchVo.setCreateBy(sysUser.getUserName());
                    for (IsfdBusinessScenariosVo isfdBusinessScenariosVo : isfdBusinessScenariosList) {
                        if(isfdBusinessScenariosVo.getId().equals(isfdBusinessDatabaseRefVo.getSceneId())){
                            isfdDatabaseModelConfigSearchVo.setSceneName(isfdBusinessScenariosVo.getName());
                        }
                    }
                    //循环systemList
                    for (IsfdBusinessScenariosVo isfdBusinessScenariosVo : isfdBusinessSystemsList) {
                        if(isfdBusinessScenariosVo.getId().equals(isfdBusinessDatabaseRefVo.getSystemId())){
                            isfdDatabaseModelConfigSearchVo.setSystemName(isfdBusinessScenariosVo.getName());
                        }
                    }
                    IsfdDatabaseTypeManagementVo refDataBase = isfdDatabaseTypeManagementMapper.selectVoById(isfdBusinessDatabaseRefVo.getDatabaseTypeId());
                    IsfdDatabaseTypeManagementVo parentDataBase = getParentDataBase(refDataBase);
                    isfdDatabaseModelConfigSearchVo.setDataBaseTypeName(parentDataBase.getDatabaseName());
                    isfdDatabaseModelConfigSearchVo.setDataBaseTypeId(parentDataBase.getId());
                    isfdDatabaseModelConfigDataList.add(isfdDatabaseModelConfigSearchVo);
                }
            }
        }
        // 记录查询历史
        if(StringUtils.isNotBlank(dataRetrievalHistoryBo.getSource()) && dataRetrievalHistoryBo.getSource().equals("unifiedSearch")){
            dataRetrievalHisSave(dataRetrievalHistoryBo);
        }
        returnVo.setSceneList(isfdBusinessScenariosReturnList);
        returnVo.setSystemList(isfdBusinessSystemsReturnList);
        returnVo.setModelList(isfdDatabaseModelConfigReturnList);
        returnVo.setDataBaseList(isfdDataBaseList);
        returnVo.setDataList(isfdDatabaseModelConfigDataList);
        return returnVo;
    }
    // 递归查询父模型
    private IsfdDatabaseModelConfigVo getParentModelId(IsfdDatabaseModelConfigVo model) {
        IsfdDatabaseModelConfigVo returnModel = null;
        if (Objects.isNull(model.getParentConfigId())) {
            returnModel = model;
        }else{
            IsfdDatabaseModelConfigVo parentModel = isfdDatabaseModelConfigMapper.selectVoById(model.getParentConfigId());
            if (Objects.nonNull(parentModel.getParentConfigId())) {
                returnModel = getParentModelId(parentModel);
            }else{
                returnModel = parentModel;
            }
        }
        return returnModel;
    }
    // 递归查询父模型
    private IsfdDatabaseTypeManagementVo getParentDataBase(IsfdDatabaseTypeManagementVo dataBase) {
        IsfdDatabaseTypeManagementVo returnDataBase = null;
        if (dataBase.getParentId() == 0) {
            returnDataBase = dataBase;
        }else{
            IsfdDatabaseTypeManagementVo parentDataBase = isfdDatabaseTypeManagementMapper.selectVoById(dataBase.getParentId());
            if (parentDataBase.getParentId() == 0) {
                returnDataBase = parentDataBase;
            }else{
                returnDataBase = getParentDataBase(parentDataBase);
            }
        }
        return returnDataBase;
    }
    @Override
    public IsfdDataRetrievalDataListVo dataRetrievalSearchWithKeyword(DataRetrievalHistoryBo dataRetrievalHistoryBo) {
        // 查询条件判断
        if(Objects.isNull(dataRetrievalHistoryBo)){
            // 返回所有的数据集合
            return null;
        }
        IsfdDataRetrievalDataListVo returnVo = new IsfdDataRetrievalDataListVo();
        // 业务场景列表
        List<IsfdBusinessScenariosVo> isfdBusinessScenariosList = new ArrayList<>();
        List<IsfdBusinessScenariosVo> isfdBusinessScenariosReturnList = new ArrayList<>();
        // 业务系统列表
        List<IsfdBusinessScenariosVo> isfdBusinessSystemsList = new ArrayList<>();
        List<IsfdBusinessScenariosVo> isfdBusinessSystemsReturnList = new ArrayList<>();
        // 模型列表
        List<IsfdDatabaseModelConfigVo> isfdDatabaseModelConfigDataList = new ArrayList<>();
        List<IsfdDatabaseModelConfigVo> isfdDatabaseModelConfigReturnList = new ArrayList<>();
        List<Map> isfdDatabaseDataReturnList = new ArrayList<>();
        // 要素库列表
        List<IsfdDatabaseTypeManagementVo> isfdDataBaseList = new ArrayList<>();
        //关联关系列表
        List<IsfdBusinessDatabaseRefVo> isfdBusinessDataBaseRefList = new ArrayList<>();
        // 查询业务系统
        isfdBusinessScenariosList = isfdBusinessScenariosMapper.selectScenariosByName(dataRetrievalHistoryBo.getSceneName(),0);
        // 查询业务场景
        isfdBusinessSystemsList = isfdBusinessScenariosMapper.selectScenariosByName(dataRetrievalHistoryBo.getSystemName(),1);
        List<IsfdDatabaseModelConfigVo> modelInfo = isfdDatabaseModelConfigMapper.selectModelByName(dataRetrievalHistoryBo.getModelName(),null,null);
        List<IsfdDatabaseModelConfigVo> filterModelInfo = new ArrayList<>();
        // 判断查询条件的结果是否有值
        Boolean hasResult = true;
        if(isfdBusinessScenariosList.size() == 0 && isfdBusinessSystemsList.size() == 0 && modelInfo.size() == 0){
            hasResult = false;
        }
        if(isfdBusinessScenariosList.size() == 0 && StringUtils.isNotBlank(dataRetrievalHistoryBo.getSceneName())){
            hasResult = false;
        }
        if(isfdBusinessSystemsList.size() == 0 && StringUtils.isNotBlank(dataRetrievalHistoryBo.getSystemName())){
            hasResult = false;
        }
        if(modelInfo.size() == 0 && StringUtils.isNotBlank(dataRetrievalHistoryBo.getModelName())){
            hasResult = false;
        }
        if(!hasResult){
            returnVo.setModelList(new ArrayList<>());
            returnVo.setSceneList(new ArrayList<>());
            returnVo.setSystemList(new ArrayList<>());
            returnVo.setDataBaseList(new ArrayList<>());
            returnVo.setDataList(new ArrayList<>());
            return returnVo;
        }
        //查询有关键字的模型列表
        if(StringUtils.isNotBlank(dataRetrievalHistoryBo.getKeyWord())){
            // 查询模型数据
            for (IsfdDatabaseModelConfigVo isfdDatabaseModelConfig : modelInfo) {
                // 查询字段信息
                List<IsfdDatabaseModelConfigFieldVo> fieldList = fieldMapper.selectVoList(
                    new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                        .eq(IsfdDatabaseModelConfigField::getModelId, isfdDatabaseModelConfig.getId())
                );
                List<IsfdDatabaseModelConfigFieldVo> keyWorldFieldList = new ArrayList();
                for (IsfdDatabaseModelConfigFieldVo isfdDatabaseModelConfigFieldVo : fieldList) {
                    if(isfdDatabaseModelConfigFieldVo.getIsKeyField().equals(1)){
                        keyWorldFieldList.add(isfdDatabaseModelConfigFieldVo);
                    }
                }
                // 遍历mongo数据库是否有数据
                if(keyWorldFieldList.size() > 0){
                    filterModelInfo.add(isfdDatabaseModelConfig);
                }
            }
            List businessScenariosIds = new ArrayList();
            List businessSystemsIds = new ArrayList();
            List dataBaseTypeIds = new ArrayList();
            for (IsfdBusinessScenariosVo isfdBusinessScenariosVo : isfdBusinessScenariosList) {
                businessScenariosIds.add(isfdBusinessScenariosVo.getId());
            }
            for (IsfdBusinessScenariosVo isfdBusinessScenariosVo : isfdBusinessSystemsList) {
                businessSystemsIds.add(isfdBusinessScenariosVo.getId());
            }
            Set parentModelIdSet = new HashSet();
            for (IsfdDatabaseModelConfigVo isfdDatabaseModelConfig : filterModelInfo) {
                if(Objects.isNull(isfdDatabaseModelConfig.getParentConfigId())){
                    parentModelIdSet.add(isfdDatabaseModelConfig.getId());
                }else{
                    IsfdDatabaseModelConfigVo modelVo = getParentModelId(isfdDatabaseModelConfig);
                    parentModelIdSet.add(modelVo.getId());
                }
            }
            isfdBusinessDataBaseRefList = IsfdBusinessDatabaseRefMapper.selectDataBaseRefByCondition(businessScenariosIds,businessSystemsIds,parentModelIdSet.stream().toList(),dataBaseTypeIds);
            if(isfdBusinessDataBaseRefList.size() ==0){
                return returnVo;
            }
            List<IsfdBusinessDatabaseRefVo> hasKeyWordDataRefList = new ArrayList<>();
            for(IsfdDatabaseModelConfigVo isfdDatabaseModelConfig : filterModelInfo){
                IsfdDatabaseModelConfigSearchVo isfdDatabaseModelConfigSearchVo = new IsfdDatabaseModelConfigSearchVo();
                Long dataBaseRefModelId = null;
                if(Objects.nonNull(isfdDatabaseModelConfig.getParentConfigId())){
                    IsfdDatabaseModelConfigVo isfdDatabaseModelConfigParent = getParentModelId(isfdDatabaseModelConfig);
                    dataBaseRefModelId =  isfdDatabaseModelConfigParent.getId();
                }else{
                    dataBaseRefModelId = isfdDatabaseModelConfig.getId();
                }
                // 判断父模型是否包含在isfdBusinessDataBaseRefList中
                for (IsfdBusinessDatabaseRefVo isfdBusinessDatabaseRefVo : isfdBusinessDataBaseRefList) {
                    if(isfdBusinessDatabaseRefVo.getParentModelId().equals(dataBaseRefModelId)){
                        // 查询mongo数据
                        // 查询字段信息
                        List<IsfdDatabaseModelConfigFieldVo> fieldList = fieldMapper.selectVoList(
                            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                                .eq(IsfdDatabaseModelConfigField::getModelId, isfdDatabaseModelConfig.getId())
                        );
                        List<IsfdDatabaseModelConfigFieldVo> keyWorldFieldList = new ArrayList();
                        for (IsfdDatabaseModelConfigFieldVo isfdDatabaseModelConfigFieldVo : fieldList) {
                            if(isfdDatabaseModelConfigFieldVo.getIsKeyField().equals(1)){
                                keyWorldFieldList.add(isfdDatabaseModelConfigFieldVo);
                            }
                        }
                        // 遍历mongo数据库是否有数据
                        if(keyWorldFieldList.size() > 0) {
                            List<Document> documents = new ArrayList<>();
                            List<Document> documentsBytime = new ArrayList<>();
                            List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions = new ArrayList<>();
                            IsfdDatabaseMongoQuery queryCondition = new IsfdDatabaseMongoQuery();
                            keyWorldFieldList.forEach(item -> {
                                IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition itemCondition = new IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition();
                                itemCondition.setFieldName(item.getFieldName().toString());
                                itemCondition.setValue(dataRetrievalHistoryBo.getKeyWord());
                                itemCondition.setLogicalOperator(IsfdMongoQueryLogicalOperatorEnum.OR.getValue());
                                itemCondition.setOperator(IsfdMongoQueryOperatorEnum.LIKE.getValue());
                                conditions.add(itemCondition);
                                queryCondition.setConditions(conditions);
                            });
                            Long tableDataCount = mongoService.count(isfdDatabaseModelConfig.getTableName(), queryCondition);
                            PageQuery pageQuery = new PageQuery();
                            pageQuery.setPageNum(1);
                            pageQuery.setPageSize(tableDataCount.intValue());
                            if (tableDataCount == 0) {
                                pageQuery.setPageSize(1);
                            }
                            queryCondition.setPageQuery(pageQuery);
                            documents = mongoService.aggregationQuery(isfdDatabaseModelConfig.getTableName(), queryCondition);
                            // 根据时间查询数据
                            if(Objects.nonNull(dataRetrievalHistoryBo.getStartTime()) && Objects.nonNull(dataRetrievalHistoryBo.getEndTime())){
                                Instant instantStart = dataRetrievalHistoryBo.getStartTime().toInstant();
                                Instant instantEnd = dataRetrievalHistoryBo.getEndTime().toInstant();
                                String isoDateStart = instantStart.toString();
                                String isoDateEnd = instantEnd.toString();
                                documentsBytime = mongoService.findByTimeRangeAndDeleteFlag(isfdDatabaseModelConfig.getTableName(), isoDateStart, isoDateEnd, null, null, 0, "created", null);

                            }
                            if (documents.size() > 0) {
                                IsfdDatabaseDataTreeQueryBo queryDataCondition = new IsfdDatabaseDataTreeQueryBo();
                                Set ids = new HashSet();
                                if(documentsBytime.size()>0){
                                    // 筛选documents里包含documentsBytime的数据
                                    for (Document document : documents) {
                                        Map dataMap = document;
                                        //子模型
                                        String dataId = (String) dataMap.get("_id");
                                        if (documentsBytime.stream().anyMatch(doc -> doc.get("_id").equals(dataId))) {
                                            ids.add(dataId);
                                        }
                                    }
                                }else{
                                    for (Document document : documents) {
                                        Map dataMap = document;
                                        //子模型
                                        String dataId = (String) dataMap.get("_id");
                                        ids.add(dataId);

                                    }
                                }
                                queryDataCondition.setModelId(isfdDatabaseModelConfig.getId());
                                queryDataCondition.setTableName(isfdDatabaseModelConfig.getTableName());
                                queryDataCondition.setObjectIds(ids.stream().toList());
                                IsfdDatabaseDataTreeResultVo dataTreeResultVo = isfdDatabaseDataManagementService.queryDataTree(queryDataCondition);
                                IsfdDatabaseTypeManagementVo refDataBase = isfdDatabaseTypeManagementMapper.selectVoById(isfdBusinessDatabaseRefVo.getDatabaseTypeId());
                                IsfdDatabaseTypeManagementVo parentDataBase = getParentDataBase(refDataBase);
                                Map dataMap = new HashMap();
                                dataMap.put("dataList", dataTreeResultVo.getContent());
                                dataMap.put("sceneId", isfdBusinessDatabaseRefVo.getSceneId());
                                dataMap.put("systemId", isfdBusinessDatabaseRefVo.getSystemId());
                                dataMap.put("dataBaseTypeId", parentDataBase.getId());
                                dataMap.put("modelId", dataBaseRefModelId);
                                if (!CollectionUtils.isEmpty(dataTreeResultVo.getContent())) {
                                    isfdDatabaseDataReturnList.add(dataMap);
                                    hasKeyWordDataRefList.add(isfdBusinessDatabaseRefVo);
                                }
                            }
                        }
                    }
                }
            }
            if(hasKeyWordDataRefList.size() == 0){
                return returnVo;
            }
            // 分组场景
            Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedSceneDatas = hasKeyWordDataRefList.stream()
                .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getSceneId));
            // 业务系统分组
            Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedSystemDatas = hasKeyWordDataRefList.stream()
                .filter(p -> p.getSystemId() != null)
                .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getSystemId));
            // 要素库分组
            Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedDataBaseDatas = hasKeyWordDataRefList.stream()
                .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getDatabaseTypeId));
            // 模型分组
            Map<Long, List<IsfdBusinessDatabaseRefVo>> groupedModelDatas = hasKeyWordDataRefList.stream()
                .collect(Collectors.groupingBy(IsfdBusinessDatabaseRefVo::getParentModelId));
            for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedSceneDatas.entrySet()) {
                Long sceneId = entry.getKey();
                IsfdBusinessScenariosVo isfdBusinessScenariosVo = isfdBusinessScenariosMapper.selectVoById(sceneId);
                isfdBusinessScenariosReturnList.add(isfdBusinessScenariosVo);
            }
            for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedSystemDatas.entrySet()) {
                Long systemId = entry.getKey();
                IsfdBusinessScenariosVo isfdBusinessScenariosVo = isfdBusinessScenariosMapper.selectVoById(systemId);
                isfdBusinessSystemsReturnList.add(isfdBusinessScenariosVo);
            }
            for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedDataBaseDatas.entrySet()) {
                Long dataBaseId = entry.getKey();
                IsfdDatabaseTypeManagementVo isfdDatabaseTypeManagementVo = isfdDatabaseTypeManagementMapper.selectVoById(dataBaseId);
                if(isfdDatabaseTypeManagementVo.getParentId() == 0){
                    isfdDataBaseList.add(isfdDatabaseTypeManagementVo);
                }else{
                    IsfdDatabaseTypeManagementVo parentDataBase = getParentDataBase(isfdDatabaseTypeManagementVo);
                    // 查询父级要素库
                    isfdDataBaseList.add(parentDataBase);
                }
            }
            //isfdDataBaseList根据id去重
            List<IsfdDatabaseTypeManagementVo> distinctList = isfdDataBaseList.stream()
                .collect(Collectors.toMap(
                    IsfdDatabaseTypeManagementVo::getId,   // 键：ID
                    e -> e,            // 值：对象本身
                    (oldVal, newVal) -> oldVal // 冲突时保留旧值
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
            // 循环模型
            for (Map.Entry<Long, List<IsfdBusinessDatabaseRefVo>> entry : groupedModelDatas.entrySet()) {
                Long modelId = entry.getKey();
                IsfdDatabaseModelConfigVo isfdDatabaseModelConfigVo = isfdDatabaseModelConfigMapper.selectVoById(modelId);
                isfdDatabaseModelConfigReturnList.add(isfdDatabaseModelConfigVo);
            }
            isfdDataBaseList = distinctList;
            returnVo.setSceneList(isfdBusinessScenariosReturnList);
            returnVo.setSystemList(isfdBusinessSystemsReturnList);
            returnVo.setModelList(isfdDatabaseModelConfigReturnList);
            returnVo.setDataBaseList(isfdDataBaseList);
            returnVo.setDataList(isfdDatabaseDataReturnList);
        }
        // 记录查询历史
        if(StringUtils.isNotBlank(dataRetrievalHistoryBo.getSource()) && dataRetrievalHistoryBo.getSource().equals("unifiedSearch")){
            dataRetrievalHisSave(dataRetrievalHistoryBo);
        }
        return returnVo;
    }

    @Override
    public Boolean dataRetrievalDeleteById(Long id) {
        if(Objects.nonNull(id)){
           return baseMapper.deleteById(id) > 0;
        }
        return true;
    }

    @Override
    public Boolean modelDatalDelete(ModelDataDeleteBo modelDataDeleteBo) {
        if(Objects.nonNull(modelDataDeleteBo.getId())){
            return mongoService.deleteByIds(modelDataDeleteBo.getTableName(), Collections.singletonList(modelDataDeleteBo.getId()));
        }
        return true;
    }

    @Override
    public List<DataRetrievalHistoryVo> dataRetrievalHistory() {
       List<DataRetrievalHistoryVo> resultList = baseMapper.dataRetrievalHistory();
       return resultList;
    }

    @Override
    public Boolean dataRetrievalHisSave(DataRetrievalHistoryBo dataRetrievalHistoryBo) {
        DataRetrievalHistory dataRetrievalHistory = MapstructUtils.convert(dataRetrievalHistoryBo, DataRetrievalHistory.class);
        LoginUser loginUser = LoginHelper.getLoginUser();
        dataRetrievalHistory.setCreateBy(loginUser.getUserId());
        dataRetrievalHistory.setUpdateBy(loginUser.getUserId());
        // 判断入参是否为空,为空则不插入查询历史记录
        Boolean flag = true;
        if(StringUtils.isNotBlank(dataRetrievalHistory.getKeyWord())
            ||StringUtils.isNotBlank(dataRetrievalHistory.getSceneName())
            ||StringUtils.isNotBlank(dataRetrievalHistory.getSystemName())
            ||StringUtils.isNotBlank(dataRetrievalHistory.getModelName())
            ||dataRetrievalHistory.getQueryStartTime()!=null
            ||dataRetrievalHistory.getQueryEndTime()!=null){
            flag = baseMapper.insert(dataRetrievalHistory) > 0;;
        }
        return flag;
    }

    @Override
    public Map<?,?> dataRetrievalView(DataRetrievalViewBo dataRetrievalViewBo) {
        // 查询mongo数据
        List<Document> documents = new ArrayList<>();
        // 查询模型数据
        IsfdDatabaseModelConfig  modelConfig = isfdDatabaseModelConfigMapper.selectById(dataRetrievalViewBo.getModelId());
        IsfdDatabaseDataTreeQueryBo queryDataCondition = new IsfdDatabaseDataTreeQueryBo();
        queryDataCondition.setModelId(modelConfig.getId());
        queryDataCondition.setTableName(modelConfig.getTableName());
        IsfdDatabaseDataTreeResultVo dataTreeResultVo = isfdDatabaseDataManagementService.queryDataTree(queryDataCondition);
        Map resultMap = new HashMap();
        resultMap.put("dataList",dataTreeResultVo);
        return resultMap;
    }

    @Override
    public List<IsfdDatabaseModelConfigVo> dataRetrievalSearchExact(DataRetrievalExectSearchBo dataRetrievalExectSearchBo) {
        List businessScenariosIds = new ArrayList<>();
        if(StringUtils.isNotBlank(dataRetrievalExectSearchBo.getSenarioIds())){
            businessScenariosIds = List.of(dataRetrievalExectSearchBo.getSenarioIds().split(","));
        }
        List businessSystemsIds =new ArrayList<>();
        if(StringUtils.isNotBlank(dataRetrievalExectSearchBo.getSystemIds())){
            businessSystemsIds = List.of(dataRetrievalExectSearchBo.getSystemIds().split(","));
        }
        List modelIds = new ArrayList<>();
        if (StringUtils.isNotBlank(dataRetrievalExectSearchBo.getModelIds())){
            modelIds =List.of(dataRetrievalExectSearchBo.getModelIds().split(","));
        }
        List dataBaseTypeIds = new ArrayList<>();
        if (StringUtils.isNotBlank(dataRetrievalExectSearchBo.getDataBaseTypeIds())){
            dataBaseTypeIds = List.of(dataRetrievalExectSearchBo.getDataBaseTypeIds().split(","));
        }

        List<IsfdDatabaseModelConfigVo> isfdDatabaseModelConfigDataList = new ArrayList<>();
        List<IsfdBusinessDatabaseRefVo> isfdBusinessDataBaseRefList = new ArrayList<>();
        isfdBusinessDataBaseRefList = IsfdBusinessDatabaseRefMapper.selectDataBaseRefByCondition(businessScenariosIds,businessSystemsIds,modelIds,dataBaseTypeIds);
        for (IsfdBusinessDatabaseRefVo isfdBusinessDatabaseRefVo : isfdBusinessDataBaseRefList) {
            // 查询业务数据
            List<IsfdDatabaseModelConfigVo> modelList = isfdDatabaseModelConfigMapper.selectModelData(isfdBusinessDatabaseRefVo.getParentModelId());
            for (IsfdDatabaseModelConfigVo isfdDatabaseModelConfig : modelList) {
                isfdDatabaseModelConfigDataList.add(isfdDatabaseModelConfig);
            }
        }
        return isfdDatabaseModelConfigDataList;
    }

    @Override
    public IsfdDataRetrievalListVo dataRetrievalSearchByHistory(Long id) {
        // 查询历史记录
//        DataRetrievalHistoryVo dataRetrievalHistoryVo = new DataRetrievalHistoryVo();
//        DataRetrievalHistory dataRetrievalHistory = MapstructUtils.convert(dataRetrievalHistoryBo, DataRetrievalHistory.class)
        DataRetrievalHistoryVo dataRetrievalHistoryVo = baseMapper.selectVoById(id);
        // 遍历查询条件
        DataRetrievalHistoryBo dataRetrievalHistoryBo = new DataRetrievalHistoryBo();
        dataRetrievalHistoryBo.setSceneName(dataRetrievalHistoryVo.getSceneName());
        dataRetrievalHistoryBo.setSystemName(dataRetrievalHistoryVo.getSystemName());
        dataRetrievalHistoryBo.setModelName(dataRetrievalHistoryVo.getModelName());
        dataRetrievalHistoryBo.setKeyWord(dataRetrievalHistoryVo.getKeyWord());
        dataRetrievalHistoryBo.setStartTime(dataRetrievalHistoryVo.getQueryStartTime());
        dataRetrievalHistoryBo.setEndTime(dataRetrievalHistoryVo.getQueryEndTime());
        return dataRetrievalSearch(dataRetrievalHistoryBo);
    }
}

